<template>
  <t-dialog v-model:visible="formVisible" :header="pwdTitle" :footer="false" attach="body">
    <t-form :data="form" @submit="changePassword">
      <t-form-item
        name="password"
        label="密码"
        :rules="[
          { required: true, message: '密码不能为空' },
          { min: 8, message: '密码长度至少为8位' },
          {
            pattern: /^(?=.*[A-Za-z])(?=.*\d)/,
            message: '密码至少包含一个字母、一个数字',
          },
        ]"
      >
        <t-input v-model="form.password" />
      </t-form-item>

      <t-form-item>
        <t-button theme="primary" type="submit">确定</t-button>
      </t-form-item>
    </t-form>
  </t-dialog>
</template>
<script lang="ts" setup>
import { MessagePlugin, SubmitContext } from 'tdesign-vue-next';
import { ref } from 'vue';

import { changePwd } from '@/api/upms/user';
import { useVisible } from '@/hooks/visible';

const pwdTitle = ref('修改密码');

const props = defineProps({
  visible: {
    type: Boolean,
    default: false,
  },
  formData: {
    type: Object,
    default: () => {
      return {};
    },
  },
});

const emit = defineEmits<{
  (e: 'update:visible', v: boolean): void;
}>();

const { formVisible, open } = useVisible(props, emit);

const form = ref(props.formData);

const changePassword = async (ctx: SubmitContext) => {
  if (ctx.validateResult === true) {
    changePwd(form.value.userId, form.value.password).then(() => {
      MessagePlugin.success('修改成功');
      formVisible.value = false;
    });
  } else {
    MessagePlugin.warning(ctx.firstError);
  }
};

open(() => {
  const { userId, title } = props.formData;
  if (userId) {
    form.value.userId = userId;
    form.value.password = '';
  }
  if (title) {
    pwdTitle.value = title;
  }
});
</script>
